autocmd!
mapclear
mapclear!
noremap / <Esc>
noremap! / <Esc>
cnoremap / <C-C>
noremap  `/ /
noremap! `/ /
map [3~ 
map! [3~ 
map OP <F1>
map! OP <F1>
map OQ <F2>
map! OQ <F2>
map OR <F3>
map! OR <F3>
map OS <F4>
map! OS <F4>
map [15~ <F5>
map! [15~ <F5>
nnoremap <F9> <C-O>
nnoremap <F10> <C-I>
set nowrap hidden ignorecase smartcase incsearch backspace=2 linebreak 
set autoindent tabstop=4 history=150 mouse=a ttymouse=xterm 
set wildmode=list:longest,full display=lastline modeline t_Co=256
set wildmenu listchars=tab:>\ ,eol:<
syntax on
hi NonText ctermfg=238
hi SpecialKey ctermfg=238
hi Statement ctermfg=250
hi Constant ctermfg=255
hi Identifier ctermfg=123
hi ErrorMsg ctermbg=143 ctermfg=0
hi Search ctermbg=238
hi clear MatchParen 
hi MatchParen ctermfg=121
hi Pmenu ctermfg=121 ctermbg=238
hi PmenuSel ctermfg=121
au VimEnter * if !argc() | cd /sdcard-ext/vimhome | e main | en | so abbrev
au VimLeavePre * exe 'normal! mL'

cnorea <expr> we ((getcmdtype()==':' && getcmdpos()<4)? 'w\|e' :'we')
cnorea <expr> wf ((getcmdtype()==':' && getcmdpos()<4)? 
	\ 'w\|e\|norm! gggqG':'we')
cnorea <expr> waq ((getcmdtype()==':' && getcmdpos()<5)? 'wa\|q':'waq')
cnorea <expr> ws ((getcmdtype()==':' && getcmdpos()<4)? 'w\|so%':'ws')
cnorea <expr> wd ((getcmdtype()==':' && getcmdpos()<4)? 'w\|bd':'wd')
cnorea <expr> wsd ((getcmdtype()==':' && getcmdpos()<5)? 'w\|so%\|bd':'wsd')

fun! PunchIn() "requires !export TZ=EST5EDT
	if bufname('%')!=#'Timecard'
		split Timecard
	endif
	let now=strftime("%l:%M %m/%d... punch [i]n / [o]ut /[q]?")
	echoh Constant | redraw | echo now 
	let io=nr2char(getchar())
	if io=~?'[io]'
		exe (search('^'.now[6:10])? '' : 'normal! Go'.now[6:10])
		exe 'normal! A'.(io==?'i'? ' ' : '>').now[0:4]
		redraw | echo "...done" | call getchar() | exe 'q'
	elseif io==?'q'
		exe 'q'
	endif
	redraw | echo "" | echoh End	
endfun
nnoremap `T :call PunchIn()<CR>

set stl=\ %l/%L\ %<%F%y%=%{strftime(\"%l:%M\ %b\ %d\ \")}
hi clear StatusLine
hi StatusLine ctermfg=250 ctermbg=238
nnoremap <silent> K :exe 'se ls='.(&ls==2?0:2)<CR>

fun! InitTextFile()
	syntax region txtShow start=/\t/ end=/\t\|\S\n/
	syntax region txtHide start=/>\t/ end=/\t\|\S\n/
	hi link txtShow Constant
	hi link txtHide NonText
	if getline(1)=~'tw='	
		nnoremap <buffer> A }b$a
		nnoremap <buffer> I {w0i
	endif
endfun
au BufNewFile,BufRead *.txt call InitTextFile()
au BufNewFile *.txt exe "norm! i>\tvim: set nowrap ts=1 tw=66 fo=aw:\t"

let s:Menu=["'Empty String'[-1]",
\	"'!rm '.(expand('%:h')=='.'? '':expand('%:h').'/')"
\		.".(expand('%:t')[0]=='.'? '':'.').expand('%:t').'.swp'",
\	"'/mnt/sdcard/download/'",
\	"'/data/data/org.connectbot/files/kbox/'"]
let s:MenuStr=join(map(copy(s:Menu),
\	"v:key.' '.(len(v:val)>44? v:val[:20].' .. '.v:val[-20:] : v:val)"),"\n")
fun! InsertMenu()
	echoh Constant | echo s:MenuStr | echoh None
	return eval(s:Menu[str2nr(nr2char(getchar()))])
endfun
fun! BufferMenu()
	let bufstr="\n" | let idx=[0]
	for b in range(1, bufnr('$'))
		let bufstr.=buflisted(b)? (len(add(idx,b))-1)
		\.(bufnr('%')==b? '*':' ').' '.matchstr(bufname(b),'[^/]*$')."\n":''
	endfor
	echoh Constant | echo bufstr | echoh None
	let sel=nr2char(getchar())
	if sel==?'x'
		let lst=join(map(split(input("Delete buffers ")),'idx[v:val]'))
		if lst
			exe 'redraw | bd! '.lst
			call BufferMenu()
		endif
	elseif str2nr(sel)
		exe 'redraw | b '.idx[sel]
	endif
endfun
nnoremap <F7> :call BufferMenu()<CR>
noremap! <F7> <C-R>=InsertMenu()<CR>

let s:scrollBegin=0
let s:scrollX=0
let s:Dots  =join(map(range(1,500),'"."'),'')
let s:Spaces=join(map(range(1,500),'" "'),'')
let s:Dashes=join(map(range(1,500),'"-"'),'')
let s:speed=[1,2,4,7,11,16,22,29,37,46,56]
let g:VMode=0
let g:winNr=0
fun! OnScrollDrag()
	if g:VMode==1
		let cdiff=virtcol("'v")-wincol()
		let rdiff=line("'v")-line(".")
		echo rdiff.(s:Spaces[1:(cdiff>0? wincol():virtcol("'v"))]
			\.s:Dashes[1:abs(cdiff)])[len(rdiff):]
		if line('.')==line('w$')
			norm! 
		elseif line('.')==line('w0')
			norm! 
		endif
	elseif g:VMode==2
		let abs_pos=winline()
		for i in range(1,winnr()-1)
			let abs_pos+=winheight(i)
		endfor
		if g:winNr==1 && winnr('$')==1
			exe 'res '.(abs_pos+1)
		elseif g:winNr==1
			exe "norm! 1\<C-W>\<C-W>"	
			exe 'res '.abs_pos
			norm! L
		elseif g:winNr==winnr('$')
			exe "norm! 999\<C-W>\<C-W>"	
			exe 'res '.(&lines-abs_pos-winnr('$'))
			norm! H
		elseif winnr()<g:winNr	
			for i in range(g:winNr-1,1,-1)
				if winheight(i)>1
					exe "norm! ".i."\<C-W>\<C-W>"	
					exe 'res -1'
					exe "norm! ".999."\<C-W>\<C-W>"	
					exe 'res +1'
					exe "norm! ".g:winNr."\<C-W>\<C-W>"	
					break
				endif
			endfor
		elseif winnr()>g:winNr
			let absh=0
			for i in range(1,g:winNr-1)
				let absh+=winheight(i)
			endfor
			let max=&lines-1-absh-2*winnr('$')+g:winNr
			exe 'norm! '.g:winNr."\<C-W>\<C-W>"	
			exe 'res '.min([max,abs_pos-absh])
			norm! L
		else
			let max=&lines-1-abs_pos+winline()-2*winnr('$')+g:winNr
			exe 'res '.min([max,winline()])
		endif
	elseif !s:scrollBegin
		let g:vesave=&ve
		se ve=all
		let s:scrollBegin=winline()
		let s:scrollX=wincol()
	else
	    let change=wincol()-s:scrollX
	    let s:scrollX+=change
	    if change
	    	exe 'norm! '.abs(change).(change>0? "z\<left>" : "z\<right>")
	    endif
	    let change=winline()-s:scrollBegin
	    let s:scrollBegin+=change
	    if change
	    	exe 'norm! '.s:speed[abs(change)].(change>0? "\<C-Y>":"\<C-E>")
	    	redraw | echo s:Dots[2:line('w0')*&columns/line('$')]
	    elseif !g:VMode && line('.')==line('$')
	    	exe "norm! \<C-Y>"
	    endif
	endif
endfun
fun! OnScrollRelease()
	let s:scrollBegin=0
	if g:VMode==1
		norm! v`v
	endif
	let g:VMode=0
	exe 'se ve='.g:vesave
endfun
nnoremap <silent> <leftmouse> <leftmouse>:call OnScrollDrag()<CR>
nnoremap <silent> <leftrelease> <leftmouse>:call OnScrollRelease()<CR>
nnoremap <silent> v<leftmouse> mv:let g:VMode=1<CR>
fun! InitResize() "todo vsplit drag, account for line($)
	let g:VMode=2
	let g:winNr=winnr()
	call OnScrollDrag()
endfun
nnoremap <silent> r<leftmouse> <leftmouse>:call InitResize()<CR>
"todo horizontal scroll for visual select
"todo long press links

fun! CapWait(prev)
	redraw
	let next=nr2char(getchar())
	if next=~'[.?!\r\n[:blank:]]'
		exe 'normal! i' . next . "\<Right>"
		return CapWait(next)
	elseif next=~'[\e\/]'
		return "\<del>"
	elseif a:prev=~'[\r\n[:blank:]]'
		return toupper(next) . "\<del>"
	else
		return next . "\<del>"
	endif
endfun
fun! CapHere()
	let trunc = getline(".")[0:col(".")-2] 
	return col(".")==1 ? CapWait("\r")
	\	: trunc=~'[?!.]\s*$\|^\s*$' ? CapWait(trunc[-1:-1])
	\	: "\<del>"
endfun
imap <silent> . ._<Left><C-R>=CapWait('.')<CR>
imap <silent> ? ?_<Left><C-R>=CapWait('?')<CR>
imap <silent> ! !_<Left><C-R>=CapWait('!')<CR>
imap <silent> <CR> <CR>_<Left><C-R>=CapWait("\r")<R>
imap <silent> <NL> <NL>_<Left><C-R>=CapWait("\n")<CR>
nmap <silent> O O_<Left><C-R>=CapWait("\r")<CR>
nmap <silent> o o_<Left><C-R>=CapWait("\r")<CR>
nmap <silent> a a_<Left><C-R>=CapHere()<CR>
nmap <silent> A $a_<Left><C-R>=CapHere()<CR>
nmap <silent> i i_<Left><C-R>=CapHere()<CR>
nmap <silent> I I_<Left><C-R>=CapHere()<CR>
